# coding=utf-8
# author=haishan09@gmail.com
from collections import OrderedDict 
from chart.adapters.base import BaseAdapter
from utils.types import OrderedDefaultDict
from common.provider import provider_register


@provider_register('chartadapter', 'pie')
class PieAdapter(BaseAdapter):

    def transform(self, config, source):
        legend = []
        cells = OrderedDefaultDict(lambda: int)
        dimensions = map(lambda d: d['drilldown'], config['drilldowns'])
        aggregates = map(lambda d: d['aggregate'], config['aggregates'])
        legend_max_len = int(config['chart']['legend.max.length'])
        aggs_cnt = len(aggregates)
        if len(dimensions) == 0:
            for agg_name in aggregates:
                agg_label = self.get_agg_label(agg_name)
                legend.append(agg_label)
            for cell in source['cells']:
                for agg_name in aggregates:
                    agg_label = self.get_agg_label(agg_name)
                    value = cell.get(agg_name, 0)
                    cells[agg_label] = value 
        elif len(dimensions) > 0:
            for cell in source['cells']:
                legend_item_dim_prefix = '_'.join(map(lambda n: cell[n], dimensions))
                for agg_name in aggregates:
                    agg_label = self.get_agg_label(agg_name)
                    if aggs_cnt > 1:
                        legend_item = legend_item_dim_prefix + '_' + agg_label.decode('utf-8')
                    else:
                        legend_item = legend_item_dim_prefix
                    value = cell.get(agg_name, 0)
                    cells[legend_item] = value
                    if legend_item not in legend:
                        legend.append(legend_item)
        retdict = {}
        cells_items = cells.items()
        retdict['legend'] = legend[:legend_max_len]
        retdict['cells'] = OrderedDict(map(lambda (k, v): (k, v), cells_items[:legend_max_len]))
        if len(legend) > legend_max_len:
            retdict['legend'] += [u'其他']
            retdict['cells'][u'其他'] = sum(v for (k, v) in cells_items[legend_max_len:])
        return retdict

